package com.zzb.weixin.json;

import java.util.Map;

import com.zzb.weixin.org.json.JSONArray;
import com.zzb.weixin.org.json.JSONException;
import com.zzb.weixin.org.json.JSONObject;

public class JsonObject {
	private JSONObject jo;

	public JsonObject() {
		this.setJo(new JSONObject());
	}

	public JsonObject(JSONObject jo) {
		this.setJo(jo);
	}

	public String getAsString(String key) {
		return getJo().optString(key);
	}

	public int getAsInt(String key) {
		return getJo().optInt(key);
	}
	public long getAsLong(String key) {
		return getJo().optLong(key);
	}


	public JsonArray getAsJsonArray(String key) {
		JSONArray jsonArray = getJo().optJSONArray(key);
		if (jsonArray != null) {
			JsonArray ja = new JsonArray();
			ja.setJa(jsonArray);
			return ja;
		}
		return null;
	}

	public JsonObject getAsJsonObject(String key) {
		JSONObject jsonObject = getJo().optJSONObject(key);
		if (jsonObject != null) {
			JsonObject jo = new JsonObject();
			jo.setJo(jsonObject);
			return jo;
		}
		return null;
	}

	public void put(String property, String value) {
		try {
			getJo().put(property, value);
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
	public void put(String property, int value) {
		try {
			getJo().put(property, value);
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	public void put(String property, JsonObject value) {
		try {
			getJo().put(property, value.getJo());
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	public void put(String property, JsonArray value) {
		try {
			getJo().put(property, value.getJa());
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	public JSONObject getJo() {
		return jo;
	}

	@Override
	public String toString() {
		return getJo().toString();
	}

	public void setJo(JSONObject jo) {
		this.jo = jo;
	}

	public static Object fromObject(Map<String, String> nativeObj) {
		JsonObject jo = new JsonObject();
		for (String key : nativeObj.keySet()) {
			jo.put(key, nativeObj.get(key));
		}
		return jo;
	}
}
